<template>
  <div class="hierarchy-management">
    <!-- 头部卡片 -->
    <el-card class="header-card" shadow="never">
      <div class="header">
        <h2>层级管理</h2>
        <div class="header-actions">
          <el-button type="success" @click="createPage">
            创建页面
          </el-button>
          <el-button type="warning" @click="createCategory">
            创建分类
          </el-button>
          <el-button @click="manageHierarchy">
            管理层级
          </el-button>
          <el-button type="primary" @click="refreshData">
            刷新数据
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 层级树卡片 -->
    <el-card class="tree-card" shadow="never">
      <div class="hierarchy-content" v-loading="loading.global">
        <HierarchyTree
          :hierarchy-data="hierarchyData"
          :pages="pages"
          :categories="categories"
          :items="items"
          :expanded-keys="expandedKeys"
          @node-expand="handleNodeExpand"
          @node-collapse="handleNodeCollapse"
          @edit-page="editPage"
          @edit-category="editCategory"
          @edit-item="editItem"
          @delete-page="deletePage"
          @delete-category="deleteCategory"
          @delete-item="deleteItem"
          @view-content="viewContent"
          @manage-page="managePage"
          @manage-category="manageCategory"
          @manage-item="manageItem"
        />
      </div>
    </el-card>

    <!-- 页面表单对话框 -->
    <PageForm
      v-model:visible="pageFormVisible"
      :form-data="currentPage"
      :is-edit="isEditPage"
      :all-categories="categories"
      @save="handleSavePage"
      @cancel="closePageForm"
    />

    <!-- 分类表单对话框 -->
    <CategoryForm
      v-model:visible="categoryFormVisible"
      :form-data="currentCategory"
      :is-edit="isEditCategory"
      :pages="pages"
      :items="items"
      :temp-page-relations="tempCategoryPageRelations"
      :temp-item-relations="tempCategoryItemRelations"
      @save="handleSaveCategory"
      @cancel="closeCategoryForm"
      @add-page="addPageToCategory"
      @remove-page="removePageFromCategory"
      @add-item="addItemToCategory"
      @remove-item="removeItemFromCategory"
    />

    <!-- 项目表单对话框 -->
    <ItemForm
      v-model:visible="itemFormVisible"
      :form-data="currentItem"
      :is-edit="isEditItem"
      :categories="categories"
      :temp-category-relations="tempItemCategoryRelations"
      @save="handleSaveItem"
      @cancel="closeItemForm"
      @add-category="addCategoryToItem"
      @remove-category="removeCategoryFromItem"
      @upload-image="handleUploadImage"
    />

    <!-- 内容查看对话框 -->
    <ContentViewer
      v-model:visible="contentViewerVisible"
      :content="viewerContent"
      :title="viewerTitle"
      :type="viewerType"
    />
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import HierarchyTree from './HierarchyTree.vue'
import PageForm from './PageForm.vue'
import CategoryForm from './CategoryForm.vue'
import ItemForm from './ItemForm.vue'
import ContentViewer from './ContentViewer.vue'

// Props
const props = defineProps({
  hierarchyData: {
    type: Array,
    default: () => []
  },
  pages: {
    type: Array,
    default: () => []
  },
  categories: {
    type: Array,
    default: () => []
  },
  items: {
    type: Array,
    default: () => []
  },
  loading: {
    type: Object,
    default: () => ({ global: false })
  },
  tempCategoryPageRelations: {
    type: Array,
    default: () => []
  },
  tempCategoryItemRelations: {
    type: Array,
    default: () => []
  },
  tempItemCategoryRelations: {
    type: Array,
    default: () => []
  }
})

// Events
const emit = defineEmits([
  'save-page',
  'save-category', 
  'save-item',
  'delete-page',
  'delete-category',
  'delete-item',
  'add-page-to-category',
  'remove-page-from-category',
  'add-item-to-category',
  'remove-item-from-category',
  'add-category-to-item',
  'remove-category-from-item',
  'upload-image',
  'refresh-data'
])

// 响应式数据
const expandedKeys = ref([])
const pageFormVisible = ref(false)
const categoryFormVisible = ref(false)
const itemFormVisible = ref(false)
const contentViewerVisible = ref(false)
const currentPage = ref({})
const currentCategory = ref({})
const currentItem = ref({})
const isEditPage = ref(false)
const isEditCategory = ref(false)
const isEditItem = ref(false)
const viewerContent = ref('')
const viewerTitle = ref('')
const viewerType = ref('text')

// 展开全部函数 - 需要在 watch 之前定义
const expandAll = () => {
  const allKeys = []
  
  // 基于hierarchyData生成展开键
  if (props.hierarchyData && props.hierarchyData.length > 0) {
    props.hierarchyData.forEach(page => {
      if (page && page.id) {
        allKeys.push(`page-${page.id}`)
        
        if (page.categories && page.categories.length > 0) {
          page.categories.forEach(category => {
            if (category && category.id) {
              allKeys.push(`category-${category.id}`)
            }
          })
        }
      }
    })
  }
  
  expandedKeys.value = allKeys
}

// 收起全部
const collapseAll = () => {
  expandedKeys.value = []
}

// 监听层级数据变化，自动展开所有节点
watch(() => props.hierarchyData, (newData) => {
  if (newData && newData.length > 0) {
    expandAll()
  }
}, { immediate: true })

// 节点展开处理
const handleNodeExpand = (nodeKey) => {
  if (!expandedKeys.value.includes(nodeKey)) {
    expandedKeys.value.push(nodeKey)
  }
}

// 节点收起处理
const handleNodeCollapse = (nodeKey) => {
  const index = expandedKeys.value.indexOf(nodeKey)
  if (index > -1) {
    expandedKeys.value.splice(index, 1)
  }
}

// 刷新数据
const refreshData = () => {
  emit('refresh-data')
}

/**
 * 创建新页面
 * 打开页面创建表单对话框
 */
const createPage = () => {
  currentPage.value = {
    title: '',
    content: '',
    status: 'active'
  }
  isEditPage.value = false
  pageFormVisible.value = true
}

/**
 * 创建新分类
 * 打开分类创建表单对话框
 */
const createCategory = () => {
  currentCategory.value = {
    name: '',
    description: '',
    status: 'active'
  }
  isEditCategory.value = false
  categoryFormVisible.value = true
}

/**
 * 管理层级
 * 提供层级管理功能，如展开/收起全部等
 */
const manageHierarchy = () => {
  ElMessageBox.confirm(
    '请选择层级管理操作',
    '层级管理',
    {
      confirmButtonText: '展开全部',
      cancelButtonText: '收起全部',
      distinguishCancelAndClose: true,
      type: 'info'
    }
  ).then(() => {
    // 展开全部
    expandAll()
    ElMessage.success('已展开全部节点')
  }).catch((action) => {
    if (action === 'cancel') {
      // 收起全部
      collapseAll()
      ElMessage.success('已收起全部节点')
    }
  })
}

// 编辑页面
const editPage = (page) => {
  currentPage.value = { ...page }
  isEditPage.value = true
  pageFormVisible.value = true
}

// 编辑分类
const editCategory = (category) => {
  currentCategory.value = { ...category }
  isEditCategory.value = true
  categoryFormVisible.value = true
}

// 编辑项目
const editItem = (item) => {
  currentItem.value = { ...item }
  isEditItem.value = true
  itemFormVisible.value = true
}

// 管理页面
const managePage = (page) => {
  // 可以在这里添加页面管理的逻辑，比如跳转到页面详情管理
  ElMessage.info(`管理页面: ${page.name}`)
}

// 管理分类
const manageCategory = (category) => {
  // 可以在这里添加分类管理的逻辑
  ElMessage.info(`管理分类: ${category.name}`)
}

// 管理项目
const manageItem = (item) => {
  // 可以在这里添加项目管理的逻辑
  ElMessage.info(`管理项目: ${item.name}`)
}

// 关闭表单
const closePageForm = () => {
  pageFormVisible.value = false
  currentPage.value = {}
  isEditPage.value = false
}

const closeCategoryForm = () => {
  categoryFormVisible.value = false
  currentCategory.value = {}
  isEditCategory.value = false
}

const closeItemForm = () => {
  itemFormVisible.value = false
  currentItem.value = {}
  isEditItem.value = false
}

// 保存处理
const handleSavePage = (pageData) => {
  emit('save-page', pageData, isEditPage.value)
  closePageForm()
}

const handleSaveCategory = (categoryData) => {
  emit('save-category', categoryData, isEditCategory.value)
  closeCategoryForm()
}

const handleSaveItem = (itemData) => {
  emit('save-item', itemData, isEditItem.value)
  closeItemForm()
}

// 删除处理
const deletePage = async (page) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除页面 "${page.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-page', page.id)
  } catch {
    // 用户取消删除
  }
}

const deleteCategory = async (category) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类 "${category.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-category', category.id)
  } catch {
    // 用户取消删除
  }
}

const deleteItem = async (item) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除项目 "${item.title}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    emit('delete-item', item.id)
  } catch {
    // 用户取消删除
  }
}

// 查看内容
const viewContent = (data) => {
  viewerTitle.value = data.title || data.name
  
  if (data.type) {
    // 项目内容
    switch (data.type) {
      case 'markdown':
        viewerContent.value = data.content || '暂无内容'
        viewerType.value = 'markdown'
        break
      case 'external':
        viewerContent.value = data.url || '暂无链接'
        viewerType.value = 'url'
        break
      case 'page':
        viewerContent.value = `页面ID: ${data.page_id || '未设置'}`
        viewerType.value = 'text'
        break
      case 'component':
        viewerContent.value = `组件名称: ${data.component_name || '未设置'}\n参数: ${data.params || '{}'}`
        viewerType.value = 'text'
        break
      default:
        viewerContent.value = '暂无内容'
        viewerType.value = 'text'
    }
  } else if (data.content !== undefined) {
    // 页面内容
    viewerContent.value = data.content || '暂无内容'
    viewerType.value = 'text'
  } else {
    // 分类内容
    viewerContent.value = data.description || '暂无描述'
    viewerType.value = 'text'
  }
  
  contentViewerVisible.value = true
}

// 关系管理
const addPageToCategory = (categoryId, pageId) => {
  emit('add-page-to-category', categoryId, pageId)
}

const removePageFromCategory = (categoryId, pageId) => {
  emit('remove-page-from-category', categoryId, pageId)
}

const addItemToCategory = (categoryId, itemId) => {
  emit('add-item-to-category', categoryId, itemId)
}

const removeItemFromCategory = (categoryId, itemId) => {
  emit('remove-item-from-category', categoryId, itemId)
}

const addCategoryToItem = (itemId, categoryId) => {
  emit('add-category-to-item', itemId, categoryId)
}

const removeCategoryFromItem = (itemId, categoryId) => {
  emit('remove-category-from-item', itemId, categoryId)
}

// 根据ID删除页面分类关系
const removePageCategoryRelationById = (relationId) => {
  // 这里可以添加具体的删除逻辑
  console.log('删除页面分类关系:', relationId)
}

// 根据ID删除分类项目关系
const removeCategoryItemRelationById = (relationId) => {
  // 这里可以添加具体的删除逻辑
  console.log('删除分类项目关系:', relationId)
}

// 删除页面项目关系
const removePageItemRelation = (pageId, itemId) => {
  // 这里可以添加具体的删除逻辑
  console.log('删除页面项目关系:', pageId, itemId)
}

// 图片上传
const handleUploadImage = (file) => {
  emit('upload-image', file)
}
</script>

<style scoped>
/* 主容器样式 - 极简扁平设计 */
.hierarchy-management {
  padding: 0;
  /* background: white; */
  height: calc(100vh - 40px);
  display: flex;
  flex-direction: column;
}

/* 头部卡片样式 */
.header-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-card :deep(.el-card__body) {
  padding: 0;
}

/* 树形卡片样式 */
.tree-card {
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  flex: 0 1 auto;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 200px;
  max-height: 85vh;
}

.tree-card :deep(.el-card__body) {
  padding: 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 头部样式 - 现代化设计 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  position: relative;
  overflow: hidden;
}

.header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0.05) 100%);
  pointer-events: none;
}

.header h2 {
  margin: 0;
  color: white;
  font-size: 24px;
  font-weight: 600;
  letter-spacing: -0.025em;
  text-shadow: 0 2px 4px rgba(0,0,0,0.1);
  position: relative;
  z-index: 1;
}

.header-actions {
  display: flex;
  gap: 12px;
  position: relative;
  z-index: 1;
}

/* 内容区域 - 现代化布局 */
.hierarchy-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  background: white;
  position: relative;
}

/* 现代化按钮样式 */
:deep(.el-button) {
  padding: 10px 20px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  border-radius: 8px !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border: 1px solid transparent !important;
  min-height: 36px !important;
  letter-spacing: 0.025em !important;
  position: relative !important;
  overflow: hidden !important;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05) !important;
}

:deep(.el-button::before) {
  content: '' !important;
  position: absolute !important;
  top: 0 !important;
  left: -100% !important;
  width: 100% !important;
  height: 100% !important;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent) !important;
  transition: left 0.5s !important;
}

:deep(.el-button:hover::before) {
  left: 100% !important;
}

:deep(.el-button--default) {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%) !important;
  color: #64748b !important;
  border: 1px solid #e2e8f0 !important;
}

:deep(.el-button--default:hover) {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%) !important;
  color: #475569 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1) !important;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  border: 1px solid #667eea !important;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%) !important;
  border-color: #5a6fd8 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3) !important;
}

:deep(.el-button--success) {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
  color: white !important;
  border: 1px solid #10b981 !important;
}

:deep(.el-button--success:hover) {
  background: linear-gradient(135deg, #059669 0%, #047857 100%) !important;
  border-color: #059669 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 20px rgba(16, 185, 129, 0.3) !important;
}

:deep(.el-button--warning) {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
  color: white !important;
  border: 1px solid #f59e0b !important;
}

:deep(.el-button--warning:hover) {
  background: linear-gradient(135deg, #d97706 0%, #b45309 100%) !important;
  border-color: #d97706 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 20px rgba(245, 158, 11, 0.3) !important;
}

:deep(.el-button--danger) {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
  color: white !important;
  border: 1px solid #ef4444 !important;
}

:deep(.el-button--danger:hover) {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%) !important;
  border-color: #dc2626 !important;
  transform: translateY(-1px) !important;
  box-shadow: 0 6px 20px rgba(239, 68, 68, 0.3) !important;
}

/* 图标样式 - 极简设计 */
:deep(.el-icon) {
  margin-right: 4px !important;
  font-size: 14px !important;
  color: #64748b !important;
}

/* 对话框按钮样式 */
:deep(.el-dialog__footer .el-button) {
  padding: 8px 16px !important;
  font-size: 14px !important;
  min-height: 32px !important;
  min-width: 70px !important;
}

/* 表格操作按钮样式 */
:deep(.el-table .el-button) {
  padding: 4px 8px !important;
  font-size: 12px !important;
  min-height: 28px !important;
  min-width: 50px !important;
}

/* 分页组件样式 - 极简扁平 */
:deep(.el-pagination) {
  padding: 20px 0 !important;
  background: transparent !important;
  justify-content: center !important;
}

:deep(.el-pagination .el-pager li) {
  background: transparent !important;
  border: 1px solid #e2e8f0 !important;
  border-radius: 0 !important;
  margin: 0 1px !important;
  font-weight: 400 !important;
  min-width: 36px !important;
  height: 36px !important;
  color: #64748b !important;
  transition: background-color 0.15s ease !important;
}

:deep(.el-pagination .el-pager li:hover) {
  background: #f8fafc !important;
  color: #475569 !important;
}

:deep(.el-pagination .el-pager li.is-active) {
  background: #667eea !important;
  color: white !important;
  border-color: #667eea !important;
}

/* 现代化标签样式 */
:deep(.el-tag) {
  padding: 4px 12px !important;
  font-size: 12px !important;
  font-weight: 500 !important;
  border-radius: 20px !important;
  border: none !important;
  transition: all 0.3s ease !important;
  position: relative !important;
  overflow: hidden !important;
  letter-spacing: 0.025em !important;
}

:deep(.el-tag::before) {
  content: '' !important;
  position: absolute !important;
  top: 0 !important;
  left: -100% !important;
  width: 100% !important;
  height: 100% !important;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent) !important;
  transition: left 0.5s !important;
}

:deep(.el-tag:hover::before) {
  left: 100% !important;
}

:deep(.el-tag--success) {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2) !important;
}

:deep(.el-tag--success:hover) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3) !important;
}

:deep(.el-tag--warning) {
  background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(245, 158, 11, 0.2) !important;
}

:deep(.el-tag--warning:hover) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(245, 158, 11, 0.3) !important;
}

:deep(.el-tag--danger) {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2) !important;
}

:deep(.el-tag--danger:hover) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3) !important;
}

:deep(.el-tag--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
  color: white !important;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.2) !important;
}

:deep(.el-tag--primary:hover) {
  transform: translateY(-1px) !important;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3) !important;
}

/* 现代化滚动条样式 */
:deep(::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(::-webkit-scrollbar-track) {
  background: rgba(0,0,0,0.05);
  border-radius: 4px;
}

:deep(::-webkit-scrollbar-thumb) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 4px;
  transition: background 0.3s ease;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
}

:deep(::-webkit-scrollbar-corner) {
  background: transparent;
  border-radius: 0;
}

:deep(::-webkit-scrollbar-thumb:hover) {
  background: #cbd5e1;
}
</style>